package com.qianfeng.openplatform.zuul.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.qianfeng.openplatform.common.BaseResultBean;
import com.qianfeng.openplatform.common.CommonsConstants;
import com.qianfeng.openplatform.common.SystemParams;
import com.qianfeng.openplatform.zuul.feign.CacheFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @Author LJF
 * @Date 2020/8/6 16:11
 * @Version 1.0
 */
@Component
public class SystemParamsFilter extends ZuulFilter {

    @Autowired
    private CacheFeign cacheFeign;

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        try {
            Set<Object> objects = cacheFeign.sMembers(SystemParams.SYSTEMPARAMS);
            if(objects!=null && objects.size()>0){
                for (Object object : objects) {
                    String value = request.getParameter(object.toString());
                    if (StringUtils.isEmpty(value)){
                        //拦截请求，返回一些错误
                        context.setSendZuulResponse(false);
                        BaseResultBean resultBean = new BaseResultBean();
                        resultBean.setCode(CommonsConstants.PARAMETER_MISSED);
                        resultBean.setMsg("必须传递参数名为:"+object+"的数据");
                        context.getResponse().setContentType("application/json;charset=utf-8");
                        context.setResponseBody(objectMapper.writeValueAsString(resultBean));
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return null;
    }
}
